<template>
  <div>
    <div class="pubmusicScore-container">
      <el-form ref="optionForm" :model="optionForm">
        <el-card class="pubmusicScore-content">
          <div class="title-content">
            <input
              class="title"
              maxlength="50"
              placeholder="😊输入歌名，不用《》噢"
              v-model="optionForm.title"
            />
            <div style="margin-left:auto;">
              {{ optionForm.title.length }}/50
            </div>
          </div>
          <div>
            <el-form-item label="*乐谱" prop="referenced_urls">
              <div slot="label"><i style="color:red;">*</i>乐谱</div>
              <UploadMusicScore
                :referenced_urls="this.optionForm.referenced_urls"
              />
            </el-form-item>
            <div class="publish-info">
              支持照片类型上传，不支持PDF上传!<br />
              PDF推荐上传文件库。
              <strong>
                <a href="https://www.123pan.com/s/X7eA-QafUh.html"
                  >点我下载PDF转照片工具(win)</a
                >
              </strong>
            </div>
          </div>
        </el-card>
        <el-card class="option-container">
          <el-form-item label="描述" prop="content" class="description">
            <div slot="label"><i style="color:red;">*</i>描述</div>

            <el-input
              :autosize="{ minRows: 3 }"
              type="textarea"
              class="description-input"
              v-model="optionForm.content"
            ></el-input>
          </el-form-item>
          <el-form-item label="付费" prop="paid_product">
            <el-switch
              v-model="optionForm.paid_product"
              active-color="#0064fa"
              inactive-color="#f4f5f5"
            >
            </el-switch>
          </el-form-item>
          <el-form-item
            label="价格"
            prop="cost"
            v-show="optionForm.paid_product"
          >
            <el-input-number
              :disabled="!optionForm.paid_product"
              v-model="optionForm.cost"
              :precision="2"
              :step="1"
              size="mini"
            ></el-input-number>
          </el-form-item>
          <el-form-item prop="tag_ids">
            <div slot="label"><i style="color:red;">*</i>标签</div>

            <el-tag
              :key="tag.id"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.tag_name }}
            </el-tag>
            <el-button
              class="button-new-tag"
              size="small"
              @click="showTagDialog"
            >
              <i class="el-icon-circle-plus-outline"></i>
              添加标签</el-button
            >
          </el-form-item>
          <!-- <div class="publish-info">
            请选择【歌手】标签
          </div> -->
          <el-form-item prop="img_url">
            <div slot="label">
              封面
            </div>
            <UploadImage :editUrl="optionForm.img_url" />
          </el-form-item>
          <el-form-item class="option-content">
            <el-button
              class="CustomBtn"
              v-if="!isEdit"
              style="margin-left:0.8rem"
              @click="PublishmusicScore"
              >发布乐谱</el-button
            >
            <el-button
              style="margin-left:1.2rem"
              type="danger"
              v-else
              @click="EditmusicScore"
              >编辑乐谱</el-button
            >
            <!-- <el-button size="mini" @click="CancelUpload">取消</el-button> -->
          </el-form-item>
        </el-card>
      </el-form>
    </div>

    <TagDialog
      type="music_score"
      :ShowTagDialogVisible="ShowTagDialogVisible"
      @closeTagDialog="closeTagDialog"
      :tag_ids="optionForm.tag_ids"
    />
  </div>
</template>

<script>
// 引入组件

import { musicScoreTip } from '@/utils/tip'
// 注册 ImageResize 模块
import TagDialog from '@/components/Article/TagDialog'
import UploadImage from '@/components/Tools/UploadImage'
import UploadMusicScore from '@/components/MusicScore/UploadMusicScore'
export default {
  props: {},
  components: {
    TagDialog,
    UploadImage,
    UploadMusicScore
  },
  data() {
    return {
      isEdit: false,
      // 动态显示的tag
      dynamicTags: [],
      // 待删除列表
      deleteImgList: [],
      // 是否成功发布标志位
      PublishSuccess: false,
      // 选项
      optionForm: {
        content: '歌手: xxx\r制谱: xxx',
        title: '',
        img_url: '',
        cost: 0,
        referenced_urls: [],
        paid_product: false
      },
      musicScoreTip: {},
      ShowTagDialogVisible: false,
      imgList: []
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // 判断是否为编辑
    this.$nextTick(() => {
      // 绑定上传图片事件
      // 监听封面上传事件
      this.$bus.$on('UploadSuccess', this.getUploadImageUrl)
      this.$bus.$on('RemoveUploadImage', this.RemoveUploadImage)
      this.WhetherEdit()
      // 获取乐谱'提示
      this.musicScoreTip = musicScoreTip
    })
  },
  beforeDestroy() {
    // 销毁绑定事件
    this.$bus.$off('getTagsId', this.getTagList)
    this.$bus.$off('RemoveUploadImage', this.RemoveUploadImage)
    // 如果没有上传成功
    this.CancelUpload()
  },
  methods: {
    // 发布乐谱'
    async PublishmusicScore() {
      // 发起确认事件
      this.$bus.$emit('handleConfirm')
      let referenced_urls = this.$store.state.musicScore.imgList
      let file_code = this.$store.state.musicScore.file_hash
      if (!referenced_urls) return this.$message.warning('请上传乐谱')
      if (!file_code) return this.$message.warning('无任何文件')
      // 整理数据
      this.optionForm.referenced_urls = referenced_urls
      this.optionForm.file_code = file_code
      this.optionForm.paid_product = this.optionForm.paid_product ? 1 : 0
      let datas = this.$qs.stringify(this.optionForm, {
        arrayFormat: 'brackets'
      })
      const res = await this.$API.musicScore.publishMusicScore(datas)
      // 发布成功
      if (res.status == 200) {
        // 标志上传成功
        this.PublishSuccess = true
        this.$message.success('发布成功')
        this.$router.replace('/musicScore')
        // window.location.reload();
      } else {
        this.$message.error('发布失败')
      }
    },
    // 上传图片删除事件
    RemoveUploadImage(url) {
      // 清空url
      this.optionForm.img_url = ''
      this.deleteImgList.push(url)
    },
    // 编辑乐谱
    async EditmusicScore() {
      let datas = this.$qs.stringify(this.optionForm, {
        arrayFormat: 'brackets'
      })
      const res = await this.$API.musicScore.editMusicScore(datas)
      // 发布成功
      if (res.status == 200) {
        this.$message.success('发布成功')
        this.$router.replace('/musicScore')
        // window.location.reload();
      } else {
        this.$message.error('发布失败')
      }
    },
    // 关闭tag标签窗口回调
    closeTagDialog() {
      this.ShowTagDialogVisible = false
    },
    // 上传成功回调
    getUploadImageUrl(imgUrl) {
      this.optionForm.img_url = imgUrl
      // 将上传成功的图片存储待删除列表
    },
    // 删除tag
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      let tagList = this.optionForm.tag_ids.split(',')
      console.log(tag)
      this.optionForm.tag_ids = tagList
        .filter(t => {
          return tag.id != t
        })
        .join(',')
    },
    // 打开添加标签对话框
    showTagDialog() {
      this.ShowTagDialogVisible = true
      // 监听获得tags_id事件
      this.$bus.$on('getTagsId', this.getTagList)
    },
    // 获取tag列表
    getTagList(item) {
      this.optionForm.tag_ids = item.tags_id
      // 重置数组
      this.dynamicTags = []
      let tagList = []
      item.tagList.forEach(tag => {
        tagList.push(tag)
      })
      this.dynamicTags.push(...tagList)
    },
    // 判断是否是编辑乐谱'
    WhetherEdit() {
      let isEdit = this.$route.query.isEdit
      let musicScore_id = this.$route.query.id
      console.log(this.$route.query)
      // 如果不是edit就结束
      if (!isEdit || !musicScore_id) return
      this.isEdit = isEdit
      this.getEditmusicScore(musicScore_id)
    },
    CancelUpload() {},
    // 获取乐谱'列表
    async getEditmusicScore(musicScore_id) {
      const res = await this.$API.musicScore.getMusicScoreById(musicScore_id)
      if (res.status == 200) {
        // 整理参数

        // 获取tag列表
        this.getmusicScoreTagList(musicScore_id, res)
      }
    },
    // 获取乐谱'tag列表
    async getmusicScoreTagList(musicScore_id, { data: datas }) {
      const res = await this.$API.tags.getMusicScoreTags(musicScore_id)
      console.log('musicScore_tag', res)
      console.log('musicScoredatas', datas)
      if (res.status == 200) {
        let tag_ids = []
        // 动态显示tag
        res.data.forEach(tag => {
          tag_ids.push(tag.id)
          this.dynamicTags.push(tag)
        })
        // 获取编辑数据
        this.optionForm.tag_ids = tag_ids.join(',')
        this.optionForm.title = datas.info.music_score_title
        this.optionForm.content = datas.content
        this.optionForm.img_url = datas.info.img_url
        this.optionForm.referenced_urls = datas.referenceds
        this.optionForm.music_score_id = musicScore_id
        this.optionForm = { ...this.optionForm }
      }
    }
  }
}
</script>

<style scope>
.pubmusicScore-container {
  width: 80%;
  margin: 20px auto;
}
.pubmusicScore-content {
  width: 100%;
  margin: 20px auto;
}
.title-content {
  width: 100%;
  display: flex;
  margin-bottom: 22px;
}
.title {
  display: inline-block;
  width: 100%;
  font-size: 20px;
  color: #606266;
  font-weight: bold;
}
.description {
  display: flex;
  width: 100%;
}
.description-input {
  width: 15rem;
}
.el-tag + .el-tag {
  /* margin-left: 10px; */
}
.button-new-tag {
  /* margin-left: 10px; */
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.ql-editor {
  min-height: 50vh;
}
.option-content {
  margin-top: 50px;
}
.el-input-number__decrease,
.el-input-number__increase {
  background-color: #0064fa;
  color: #ffffff;
}
.publish-info {
  margin-bottom: 22px;
  padding: 10px;
  line-height: 1.6em;
  background-color: #ddefff;
}
</style>
